<template>
  <div class="upload-pic">
    <div class="upload-content">
      <div class="upload-title">
        请务必根据打卡日期上传朋友圈截图
      </div>
      <div class="upload-time">
        打卡日期：{{card_time}}
      </div>
      <div class="upload-wrap">
        <div class="upload-inner-wrap">
          <img class="upload-display" :src="logos" @click="uploadImg"/>
          <img v-show="has_img" class='close-icon' @click="deleteImg" src="../../assets/img/uploadPic/close-icon.png">
          <!--          <input type="file" @change="seles" ref="fileInput" accept="image/*"-->
          <!--                                       class="file"/>-->
        </div>
      </div>
    </div>
    <div class="upload-split">

    </div>
    <div class="upload-tips">
      <div class="tips-title">
        截图说明
      </div>
      <div class="tips-content">
        <p>1. 请根据指定日期上传该天朋友圈截图；<br/>2. 你可以先点击右上角，然后点击“浮窗”按钮最小化页面，返回微信截图，然后上传截图。（<span
          @click="showPerform">点击查看示意图</span> ）</p>
      </div>
      <Button :style="btStyle" :text="btntext" :dis="dis" @Click="goApply()"></Button>
    </div>
    <performPopup v-if="show_perform" v-on:closePerform="closePerform"></performPopup>
  </div>
</template>

<script>
  import OSS from 'ali-oss'
  import Button from '../../components/NewPlaying/components/Button/Index'
  import performPopup from '../../components/performPopup/index'
  import {Toast} from 'mint-ui'
  import $ from 'jquery'

  export default {
    name: "index",
    data: function () {
      return {
        canClick: true,
        logos: require('../../assets/img/uploadPic/upload.png'),
        ossImg: '',
        has_img: false,
        show_perform: false,
        open_with_close: false,
        btStyle: {
          width: '80%',
          height: '4.5rem',
          borderRadius: '5rem',
          color: '#66440a',
          backgroundColor: '#ffd000',
          boxShadow: '0 10px 24px 0 rgba(255, 208, 0, 0.4)',
          position: 'fixed',
          bottom: '2.5rem',
          left: 'calc(50% - (100% + 2rem)*0.8/2)'
        },
        dis: false,
        btntext: ' 下一步',
        card_time: '',
        img_name: '',
        need_address: 0,
        need_img: 0,
        isios: !!navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/),
      }
    },
    mounted: function () {
      //根据存储变量判断是否展示提示
      if (window.localStorage.getItem('nextHide') === 'true') {
        this.show_perform = false
      }
      // 获取奖学金初始化参数
      let data = {
        params: {
          scholarship_id: JSON.parse(window.sessionStorage.getItem('reward')).scholarship_id
        }
      }
      this.$axios.scholarship_init(data).then(res => {
        this.card_time = res.data.qing_data.date.replace(/(\d+)-(\d+)-(\d+)/, '$1年$2月$3日')
        this.img_name = res.data.qing_data.img_name
        this.need_address = res.data.qing_data.need_address
        this.need_img = res.data.qing_data.need_img
      })

    },
    methods: {
      uploadImg: function () {
        // 清空input值
        $('.file').val('')

        // 设置下次点击不默认展示弹窗
        if (window.localStorage.getItem('nextHide') === 'true') {
          if (this.has_img) {
            return false
          }
          // 调用点击上传文件
          // this.$refs.fileInput.click()
          this.seles()
        } else {
          this.show_perform = true
          this.open_with_close = true
          window.localStorage.setItem('nextHide', 'true')
        }

      },
      deleteImg: function () {
        this.has_img = false
        this.logos = require('../../assets/img/uploadPic/upload.png');
      },
      // 上传文件
      seles: function () {
        if (this.has_img) {
          return
        }
        let _this = this
        this.$wx.Upimg((res, serverId) => {
          // Indicator.open({
          //   text: '正在上传',
          //   spinnerType: 'fading-circle'
          // });
          this.$axios.media_id_get_url({
            media_id: serverId,
            user_token: _this.$Login.oauth_token.user_token,
            file_name: _this.img_name || 'askdljasldjasd.jpeg',
            type: 1
          }).then(res => {
            // Indicator.close();
            if (res.data.qing_code !== 100) {
              _this.has_img = false
              _this.logos = require('../../assets/img/uploadPic/upload.png')
              Toast({
                message: '上传失败',
                iconClass: 'iconfont icon-bangdingshibai',
                duration: 2000
              })
            } else {
              _this.ossImg = res.data.qing_data
            }
          })
          if (_this.isios) {
            this.$wx.getbaseimg(res, base => {
              this.logos = base
            })
          } else {
            this.logos = res
          }
          _this.has_img = true
        })
        // this.getsts(e.target.files)
      },
      // 上传至oss
      getsts: function (files) {
        let instance = Toast({
          message: '正在上传',
          iconClass: 'iconfont icon-shangchuanzhong',
          className: 'load-pic-icon',
          duration: 3000000
        })
        var _this = this
        this.$axios.get_sts({
          params: {
            oauth_token: this.$Login.oauth_token.oauth_token,
            user_token: this.$Login.oauth_token.user_token,
            goods_id: -1,
            file_name: this.img_name,
            type: 1
          }
        }).then(res => {
          const client = new OSS.Wrapper({
            // region: res.data.qing_data.oss_data.bucket,
            endpoint: res.data.qing_data.endpoint,
            accessKeyId: res.data.qing_data.access_key_id,
            accessKeySecret: res.data.qing_data.access_key_secret,
            stsToken: res.data.qing_data.security_token,
            bucket: res.data.qing_data.bucket
          })
          if (files) {
            const fileLen = files
            const resultUpload = [];
            for (let i = 0; i < fileLen.length; i++) {
              const file = fileLen[i];
              const storeAs = file.name;
              let localImg = ''
              // 获取图片url
              var reader = new FileReader()
              reader.readAsDataURL(files[0])
              reader.onload = e => {
                this.logos = window.URL.createObjectURL(this.dataURLtoBlob(reader.result))
                // _this.logos = this.ossImg
                // 遮挡删除按钮
                // this.has_img = true
                // instance.close()
              }
              client.multipartUpload(res.data.qing_data.path + '.' + storeAs.split('.')[1], file, {}).then((results) => {
                console.info(results.res.requestUrls[0].split('?')[0])
                if (results.res) {
                  resultUpload.push(results.res.requestUrls)
                  // alert(results.res.requestUrls[0].split('?')[0])
                  this.ossImg = results.res.requestUrls[0].split('?')[0]
                  this.has_img = true
                  this.$nextTick(() => {
                    instance.close()
                  })
                }
              }).catch((err) => {
                // 清空input值
                $('.file').val('')
                this.has_img = false
                this.logos = require('../../assets/img/uploadPic/upload.png')
                instance.close()
                // alert('上传失败');
                Toast({
                  message: '上传失败',
                  iconClass: 'iconfont icon-bangdingshibai',
                  duration: 2000
                })
              });
            }
          }
        }).catch(() => {
          instance.close()
        })
      },
      goApply: function () {
        if (this.canClick) {
          this.canClick = false
          //是否上传截图
          if (this.has_img === true) {
            //判断是否需要地址
            if (JSON.parse(window.sessionStorage.getItem('reward')).reward_type === 2 || JSON.parse(window.sessionStorage.getItem('reward')).reward_type === 3) {
              // if(this.noPicToast.close()){
              //   this.noPicToast.close()
              // }
              //跳转到地址页面
              window.sessionStorage.setItem('ossImg', this.ossImg)
              this.$router.replace({
                name: 'RewardAddress'
              })
            } else {
              let data = {
                "address_id": -1,
                "img_url": this.ossImg,
                "scholarship_id": JSON.parse(window.sessionStorage.getItem('reward')).scholarship_id
              }
              this.$axios.upload_scholarship(data).then(res => {
                if (res.data.qing_code = 100) {
                  this.$router.replace({
                    name: 'RewardSuccess'
                  })
                }
              })
            }
          } else {
            this.canClick = true
            Toast({
              message: '请上传截图',
              iconClass: 'iconfont icon-bangdingshibai',
              duration: 2000
            })
          }
        }
      },
      showPerform: function () {
        this.show_perform = true
      },
      closePerform: function () {
        this.show_perform = false
        if (this.open_with_close) {
          this.open_with_close = false
          if (this.has_img) {
            return false
          }
          // 调用点击上传文件
          // this.$refs.fileInput.click()
          this.seles()
        }
      },
      dataURLtoBlob: function (dataurl) {
        var arr = dataurl.split(',');
        var mime = arr[0].match(/:(.*?);/)[1];// 结果：   image/png
        var bstr = atob(arr[1].replace(/\s/g, ''));
        var n = bstr.length;
        var u8arr = new Uint8Array(n);
        while (n--) {
          u8arr[n] = bstr.charCodeAt(n);
        }
        return new Blob([u8arr], {type: mime});//值，类型
      }
    },
    components: {Button, performPopup}
  }
</script>

<style scoped>
  @import "../../assets/css/views/uploadPic/index.css";
</style>
